//
//  ALUserAccountViewModel.swift
//  Swift01
//
//  Created by Miaoyang on 16/4/11.
//  Copyright © 2016年 Miaoyang. All rights reserved.
//

import UIKit

//专门处理ALUserAccount 模型的相关操作,网路请求,字典转模型,归档,接档
class ALUserAccountViewModel: NSObject {
    //单利
    static let sharedInstance = ALUserAccountViewModel()
    
    private override init() {
        super.init()
        //加载账号
        userAccount = loadUserAccount()
        
    }
    //账号模型,只要拿到单利就可以全局访问到,全局通用
    var userAccount:ALUserAccount?
    
    //判断用户是否登录
    var userLogin:Bool{
        
        get {
            return userAccount != nil
        }
    }
    
    //加载账号信息
    func loadAccessToken(code:String,loadAccessTokenCallBack:(error: NSError?) -> ()){
        //1.urlString
        let urlString = accessTokenURLString
        //2.获取请求参数参数.字典
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirect_uri
            
        ]
        //发送请求
        ALNetWorkTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
            //拿到结果
            let result = responseObject as? [String:AnyObject]
            
            
            if let dict = result{
                //进行字典转模型
                self.userAccount = ALUserAccount(dict:dict)
                //保存
               self.saveUserAccount()
                //通知控制器账号加载完毕,调用闭包
                loadAccessTokenCallBack(error:nil)
                
            }
            
        }) { (task, error) in
            //通知控制器账号加载失败
         
            loadAccessTokenCallBack(error: error)
        }
    }
        //保存账号信息
         private func saveUserAccount(){
            
            if let userAccount = self.userAccount {
                //归档
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
            }
        }
        //从沙河里面解档
        
        func loadUserAccount() -> ALUserAccount? {
            
            // 解档账号,有可能有,有可能没有
            let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? ALUserAccount
            
            // 可选绑定, 判断账号是否有值,账号有值,判断是否过期
            // 测试过期时间,
            //        userAccount?.expiresDate = NSDate(timeIntervalSinceNow: -100)
            if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                
                return account
            }
            
            return nil
        }
    //MARK:获取用户信息
    func loadUserInfo(loadUserInfoCallback: (error: NSError?) -> ()){
        //守卫
        guard let access_token = userAccount?.access_token else{
            //能进来就表示没有值,没有值直接返回
            print("userAccount?.access_token没有值或者账号没有值")
            return
            
        }
        guard let uid = userAccount?.uid else{
            //能进来就表示没有值,没有值直接返回
            print("userAccount?.access_token没有值或者账号没有值")
            return
            
        }
        //URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let parameters = [
            "access_token":access_token,
            "uid":uid
     
        ]
        //发送请求
        ALNetWorkTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
            //加载用户信息成功
            if let dict = responseObject as? [String:AnyObject]{
                //将获取到的数据赋值给当前账号
                self.userAccount?.screen_name  = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                //将当前对象保存到沙盒中
                self.saveUserAccount()
            }
            
        }) { (task, error) in
                //加载用户失败
            loadUserInfoCallback(error: error)
        }
        
        
    }
    
    }

